﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Learun.Application.Web.Common
{
    public class Converter
    {   
        /// <summary>
          /// 
          /// </summary>
          /// <param name="obj"></param>
        public static string ConvertToString(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return obj.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        public static double ConvertToDouble(object obj, int? digits = null, int? roundMode = null)
        {
            try
            {
                if (string.IsNullOrEmpty(ConvertToString(obj)))
                {
                    return 0;
                }
                if (digits == null)
                {
                    return Convert.ToDouble(obj);
                }
                //取整舍弃小数位
                if (digits.Value == 0 && (roundMode != null && roundMode.Value == 0))
                {
                    return Math.Floor(Convert.ToDouble(obj));
                }
                //向上取整
                if (digits.Value == 0 && (roundMode != null && roundMode.Value == 1))
                {
                    return Math.Ceiling(Convert.ToDouble(obj));
                }
                return Math.Round(Convert.ToDouble(obj), digits.Value, MidpointRounding.AwayFromZero);
            }
            catch
            {
                return 0;
            }

        }
    }
}